import { history } from 'umi';
import React, { useState, useRef, useEffect, forwardRef, useImperativeHandle } from 'react';
import { PageContainer, FooterToolbar, PageHeader } from '@ant-design/pro-layout';
import {
  Button,
  Divider,
  message,
  Input,
  Drawer,
  Table,
  Tabs,
  Card,
  Modal,
  Tag,
  Select,
  Descriptions,
  Form,
  Radio,
  Alert,
} from 'antd';
import ProTable from '@ant-design/pro-table';

import { getGroupList } from '../../NameSpace/service';
import format from '@/utils/format';
import { pullImage, getPullStatus } from '../service.js';
import trans from '@/utils/translate';
import md5 from 'js-md5';

const { Item } = Form;


const ImagePull = (props, ref) => {
  const [imageId, setImageId] = useState(0); // 镜像 ID
  const [show, setShow] = useState(false); // 控制弹窗
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [pullState, setPullState] = useState('waiting');
  const [origin, setOrigin] = useState('public');
  const [pullObj, setPullObj] = useState({});
  const [disabled, setDisabled] = useState(false);

  const originOptions = [
    { label: trans('image.lib.public'), value: 'public' },
    { label: trans('image.lib.private'), value: 'private' },
  ];

  function changeOrigin (e) {
    setOrigin(e.target.value);
  };
  const getStatus = (status) => {
    const statuses = new Map([
      ['TASK_INIT', 'waiting'],
      ['TASK_RUNNING', 'pending'],
      ['TASK_SUCCESS', 'success'],
      ['TASK_FAIL', 'error'],
      ['TASK_NOT_RUNNING', 'waiting'],
    ]);
    return statuses.get(status);
  };
  useImperativeHandle(ref, () => ({
    open: (info={}) => {
      if (info.id) {
        setImageId(info.id);
      }
      setShow(true);
    },
    close: () => {
      setShow(false);
      setImageId(0);
      setLoading(false);
      setPullState('waiting')
      form.resetFields()
    },
  }));
  const onFinish = (e) => {
    setLoading(true);
    setPullState('pending');
    const data_ = { ...e };
    delete data_.origin;
    delete data_.username;
    console.log(data_);
    if (imageId) {
      data_.imageId = parseInt(imageId);
    }
    // data_.password = md5(data_.password);
    pullImage(data_)
      .then(function (res) {
        console.log(res,res.code==0)
        if (res.code == 0) {
          setPullState('success');
          props.success();
        } else {
          setPullState('error');
        }
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
        setPullState('error');
      });
  }

  // 首先检查有没有没有拉取完的镜像
  useEffect(() => {
    show && getPullStatus().then(res => {
      if (res && res.code === 0) {
        if (res.data.length > 0) {
          // 暂时只有一个用户组
          // const userGroupName = 'systemadmin-user-group';
          const origin = res.data.password ? 'private' : 'public';
          const task = res.data[res.data.length - 1];
          setPullObj({ ...task, ...{ origin }});
          setPullState(getStatus(task.status));
          setDisabled(task.status === 'TASK_RUNNING')
        }
      }
    })
  }, [show]);
  return (
    <div>
      <Modal
        title={trans('image.pullFromCloud')}
        visible={show}
        footer={null}
        onCancel={() => {
          ref.current.close();
        }}
        maskClosable={false}
      >

        <Form
          name="basic"
          labelCol={{ span: 5 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          form={form}
        >
          {/* <Item
            label={trans('image.lib')}
            name='origin'
            initialValue={ pullObj.origin || 'public' }
            rules={[{ required: true }]}
          >
            <Radio.Group
              value={origin}
              onChange={changeOrigin}
              options={originOptions}
              disabled={disabled}/>
          </Item> */}
          <Item
            label={trans('image.pullCmd')}
            name="command"
            rules={[{ required: true, message: trans('image.pullCmd.required') }]}
            initialValue={ pullObj.command }
          >
            <Input placeholder={trans(`image.pullCmd.tip.${origin}`)} disabled={disabled} />
          </Item>
          {/* {
            origin === 'private' && (
              <Item
                label={trans('image.userName')}
                name="user"
                rules={[{ required: true }]}
                initialValue={ pullObj.user }
            >
                <Input placeholder={trans('image.userName.required')} disabled={disabled} />
              </Item>
            )
          }
          {
            origin === 'private' && (
              <Item
                label={trans('image.password')}
                name="password"
                rules={[{ required: true, message: trans('image.password.required') }]}
                initialValue={ pullObj.password }
              >
                <Input.Password placeholder={trans('image.password.required')} disabled={disabled} />
              </Item>
            )
          } */}
          {/* <Item wrapperCol={{ offset: 12, span: 12 }}> */}
          <Item style={{position: 'relative', display: 'flex'}}>
            {/* <Alert message={} type={} closable></Alert> */}
            <div className="state" style={{ marginBottom: '10px' }}>
              {pullState === 'pending' && <div style={{ color: 'red' }}>{trans('image.pull.ing')}</div>}
              {pullState === 'success' && <div style={{ color: '#56BC8A' }}>{trans('image.pull.success')}</div>}
              {pullState === 'error' && <div style={{ color: '#539ECC' }}>{trans('image.pull.fail')}</div>}
            </div>
            {
              !disabled &&
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                style={{left: '50%', transform: 'translateX(-50%)'}}
              >
                确认
              </Button>
            }
          </Item>
        </Form>
      </Modal>
    </div>
  );
};
const FImagePull = React.forwardRef(ImagePull);
export default FImagePull;
